package com.cqie.secondhandtransaction.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cqie.secondhandtransaction.DTO.*;
import com.cqie.secondhandtransaction.aspect.AvoidRepeatSubmit;
import com.cqie.secondhandtransaction.controller.params.ProductTypeParam;
import com.cqie.secondhandtransaction.entity.AccessInfo;
import com.cqie.secondhandtransaction.entity.CollectShopInfo;
import com.cqie.secondhandtransaction.entity.ProductInfo;
import com.cqie.secondhandtransaction.entity.UserInfo;
import com.cqie.secondhandtransaction.enums.StatusEnum;
import com.cqie.secondhandtransaction.exception.BusinessException;
import com.cqie.secondhandtransaction.exception.IllegalParameterException;
import com.cqie.secondhandtransaction.mapper.*;
import com.cqie.secondhandtransaction.service.ProductInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cqie.secondhandtransaction.service.file.AliYunService;
import com.cqie.secondhandtransaction.utils.DateUtil;
import com.cqie.secondhandtransaction.utils.WebSecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品服务实现类
 * </p>
 *
 * @author gdy
 * @since 2025-02-10
 */
@Service
@Slf4j
public class ProductInfoServiceImpl extends ServiceImpl<ProductInfoMapper, ProductInfo> implements ProductInfoService {
    @Autowired
    private ProductInfoMapper productInfoMapper;
    @Autowired
    private ProductTypeMapper productTypeMapper;
    @Autowired
    private AccessInfoMapper accessInfoMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private AliYunService ossService;
    @Autowired
    private CollectShopInfoMapper collectShopInfoMapper;

    /**
     * 首页查询
     *
     * @param param
     * @return
     */
    @Override
    public DataList<ProductInfo> getProductByTypeIds(ProductTypeParam param) {
        List<Integer> typeIdList = param.getTypeIdList();
        DataList<ProductInfo> dataList = new DataList<>();
        IPage<ProductInfo> iPage = new Page<>(param.getPageNum(), param.getPageSize());

        LambdaQueryWrapper<ProductInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProductInfo::getStatus, StatusEnum.S_PUB.getCode());//查询已发布的商品
        if (StringUtils.isNotEmpty(param.getProductName())) {
            //商品名称查询条件
            queryWrapper.like(ProductInfo::getProductName, param.getProductName());
        }
        if (CollectionUtils.isNotEmpty(typeIdList)) {
            queryWrapper.in(ProductInfo::getTypeId, typeIdList);
        }

        List<ProductInfo> productInfos = productInfoMapper.selectList(iPage, queryWrapper);
        productInfos.forEach(p -> {
            //类别名称
            String typeName = productTypeMapper.selectById(p.getTypeId()).getName();
            p.setTypeName(typeName);

            List<CollectShopInfo> collectShopInfos = collectShopInfoMapper.selectList(new LambdaQueryWrapper<CollectShopInfo>().eq(CollectShopInfo::getProductId, p.getId()));
            p.setCollectionCount(CollectionUtils.isNotEmpty(collectShopInfos) ? collectShopInfos.size() : 0);

            //卖家头像
            UserInfo userInfo = Optional.ofNullable(userInfoMapper.selectById(p.getSallorBy())).orElse(new UserInfo());
            p.setSellerAvatar(userInfo.getPicture());
        });
        dataList.setDataList(productInfos);

        return dataList;
    }

    /**
     * 查询商品详情
     *
     * @param id
     * @return
     */
//    @AvoidRepeatSubmit(interval = 2000)
    @Override
    public ProductInfoDTO getProductDetail(Integer id) {
        UserDetailsDTO user = WebSecurityUtil.getCurrentUser();
        ProductInfo productInfo = productInfoMapper.selectById(id);
        if (productInfo == null) {
            throw new BusinessException("商品不存在！");
        }

        //查询商品的评价信息
        List<AccessInfo> accessInfoList = accessInfoMapper.selectList(new LambdaQueryWrapper<AccessInfo>().eq(AccessInfo::getProductId, productInfo.getId()));
        accessInfoList.forEach(accessInfo -> {
            //设置评论用户信息
            accessInfo.setUserInfo(userInfoMapper.selectById(accessInfo.getUserId()).buildAccessUserInfo());
        });

        //查询商品是否被本人评价过
        Boolean is = CollectionUtils.isNotEmpty(accessInfoList)
                && accessInfoList.stream().anyMatch(accessInfo -> accessInfo.getUserId().equals(user.getId()));

        //类别名称
        String typeName = productTypeMapper.selectById(productInfo.getTypeId()).getName();
        ProductInfoDTO dto = productInfo.toProductInfoDTO();
        dto.setTypeName(typeName);
        //商家详情
        dto.setSallorInfo(userInfoMapper.selectById(productInfo.getSallorBy()).buildAccessUserInfo());

        //查询收藏人数
        List<CollectShopInfo> collectShopInfos = collectShopInfoMapper.selectList(new LambdaQueryWrapper<CollectShopInfo>().eq(CollectShopInfo::getProductId, productInfo.getId()));
        dto.setCollectionCount(CollectionUtils.isNotEmpty(collectShopInfos) ? collectShopInfos.size() : 0);
        dto.setAccessInfoList(accessInfoList);

        //查看用户是否收藏
        boolean isCollected = false;
        long count = collectShopInfos.stream().filter(t -> Objects.equals(t.getUserId(), user.getId())).count();
        if (count > 0) {
            isCollected = true;
        }
        dto.setIsCollected(isCollected);

        //查询是否被本人评价
        dto.setIsAccessed(is);

        //更新浏览量
        productInfo.buildViewCount();
        productInfoMapper.updateById(productInfo);
        dto.setViewCount(productInfo.getViewCount());
        return dto;
    }

    /**
     * 保存、更新商品（提交审核）
     *
     * @param addDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveProduct(ProductInfoAddOrEditDTO addDTO, List<MultipartFile> pictures) {
        ProductInfo info = new ProductInfo();
        UserDetailsDTO user = WebSecurityUtil.getCurrentUser();

        if (Objects.nonNull(addDTO.getId())) {
            info = productInfoMapper.selectById(addDTO.getId());
            //删除旧的照片
            if (StringUtils.isNotEmpty(info.getPicture())) {
                ossService.deleteFilesByUrl(Arrays.asList(info.getPicture().split(",")));
            }

            if (!StatusEnum.DRAFT.getCode().equals(info.getStatus())) {
                //修改只能是草稿状态
                throw new BusinessException("已提交审核的商品无法修改！");
            }
        }

        BeanUtils.copyProperties(addDTO, info, "status", "picture");
        info.setSallorBy(user.getId());//设置商家名称
        info.setSallorName(user.getUsername());//商家名称
        info.setCount(Objects.isNull(addDTO.getCount()) ? 1 : addDTO.getCount());//库存
        info.setStatus(StatusEnum.DRAFT.getCode());//草稿

        //照片上传oss，并将url存入数据库
        if (pictures != null && !pictures.isEmpty()) {
            try {
                List<String> url = ossService.uploadFiles(pictures);
                log.info("图片url{}", url);
                info.setPicture(CollectionUtils.isNotEmpty(url) ? String.join(",", url) : "");
            } catch (IOException e) {
                throw new BusinessException("图片上传失败！");
            }
        }

        if (Objects.isNull(addDTO.getId())) {
            productInfoMapper.insert(info);
        } else {

            productInfoMapper.updateById(info);
        }
    }

    /**
     * 审核商品
     *
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void auditProduct(AuditProductDTO dto) {
        ProductInfo productInfo = productInfoMapper.selectById(dto.getId());
        if (Objects.isNull(productInfo)) {
            throw new BusinessException("商品不存在！");
        }
            productInfo.setStatus(StatusEnum.S_PUB.getCode());//发布
            productInfo.setAuditTime(DateUtil.getNowDate());

        productInfoMapper.updateById(productInfo);
    }

    /**
     * 删除商品
     *
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteProduct(Integer id) {
        ProductInfo productInfo = productInfoMapper.selectById(id);
        if (Objects.isNull(productInfo)) {
            throw new BusinessException("商品不存在！");
        }
        if (Objects.isNull(productInfo.getPicture())) {
            ossService.deleteFilesByUrl(Arrays.asList(productInfo.getPicture().split(",")));
        }

        productInfoMapper.deleteById(id);
    }

    /**
     * 根据状态查询商品
     *
     * @param param
     * @return
     */
    @Override
    public DataList<ProductInfo> getUserProductInfo(StatusDTO param) {
        if (null == param.getStatus()) {
            throw new BusinessException("状态不能为空！");
        }
        DataList<ProductInfo> dataList = new DataList<>();
        UserDetailsDTO user = WebSecurityUtil.getCurrentUser();
        LambdaQueryWrapper<ProductInfo> queryWrapper = new LambdaQueryWrapper<>();

        if (param.getStatus() == 0) {
            //卖出的
            queryWrapper.eq(ProductInfo::getSallorBy, user.getId());
            queryWrapper.eq(ProductInfo::getStatus, StatusEnum.SOLD_OUT.getCode());
            queryWrapper.orderByDesc(ProductInfo::getUpdateTime);
        } else if (param.getStatus() == 1) {
            queryWrapper.eq(ProductInfo::getSallorBy, user.getId());
            queryWrapper.eq(ProductInfo::getStatus, StatusEnum.S_PUB.getCode());//查询已发布的商品
            queryWrapper.orderByDesc(ProductInfo::getCreateTime);
        } else if (param.getStatus() == 2){
            queryWrapper.eq(ProductInfo::getSallorBy, user.getId());
            queryWrapper.eq(ProductInfo::getStatus, StatusEnum.DRAFT.getCode());
            queryWrapper.orderByDesc(ProductInfo::getCreateTime);
        } else if (param.getStatus() == 3) {
            if (user.getRole() != 0){
                throw new BusinessException("权限不足！管理员才可以查看全部待审核的商品");
            }
            queryWrapper.eq(ProductInfo::getStatus, StatusEnum.DRAFT.getCode());
            queryWrapper.orderByDesc(ProductInfo::getCreateTime);
        }

        List<ProductInfo> productInfos = productInfoMapper.selectList(queryWrapper);
        productInfos.forEach(p -> {
            //类别名称
            String typeName = productTypeMapper.selectById(p.getTypeId()).getName();
            if (StatusEnum.S_PUB.getCode().equals(p.getStatus())) {
                //已发布的返回收藏人数
                List<CollectShopInfo> collectShopInfos = collectShopInfoMapper.selectList(new LambdaQueryWrapper<CollectShopInfo>().eq(CollectShopInfo::getProductId, p.getId()));
                p.setCollectionCount(CollectionUtils.isNotEmpty(collectShopInfos) ? collectShopInfos.size() : 0);
            }
            p.setTypeName(typeName);

            //卖家头像
            p.setSellerAvatar(userInfoMapper.selectById(p.getSallorBy()).getPicture());
        });
        dataList.setDataList(productInfos);

        return dataList;
    }
}
